<template>
	<view :style="[AppSkinVar]">
		<e-loading-page :loading="loading">
			<template #icon>
				<loader></loader>
			</template>
		</e-loading-page>
		<scroll-view scroll-x="true" class="white-nowrap bg-white" :scroll-with-animation="true" :scroll-left="scrollLeft">
			<view class="tab e-flex bg-white">
				<view class="text-center e-rela fw-600" @tap="(e:any) => setTabIndex(0, e)" :class="{ 'tab-active': tabIndex == 0 }">
					{{ $t('common.全部') }}
				</view>
				<view class="text-center e-rela fw-600" @tap="(e:any) => setTabIndex(1, e)" :class="{ 'tab-active': tabIndex == 1 }">
					{{ orderIconText[0] || $t('order.待付款') }}
				</view>
				<view class="text-center e-rela fw-600" @tap="(e:any) => setTabIndex(2, e)" :class="{ 'tab-active': tabIndex == 2 }">
					{{ orderIconText[1] || $t('order.待发货') }}
				</view>
				<view class="text-center e-rela fw-600" @tap="(e:any) => setTabIndex(3, e)" :class="{ 'tab-active': tabIndex == 3 }">
					{{ orderIconText[2] || $t('order.待收货') }}
				</view>
				<view class="text-center e-rela fw-600" @tap="(e:any) => setTabIndex(4, e)" :class="{ 'tab-active': tabIndex == 4 }">
					{{ orderIconText[3] || $t('order.待评价') }}
				</view>
				<view class="text-center e-rela fw-600" @tap="(e:any) => setTabIndex(5, e)" :class="{ 'tab-active': tabIndex == 5 }">
					{{ orderIconText[4] || $t('order.退款中') }}
				</view>
				<view class="text-center e-rela fw-600" @tap="(e:any) => setTabIndex(6, e)" :class="{ 'tab-active': tabIndex == 6 }">
					{{ $t('order.已完成') }}
				</view>
				<view class="text-center e-rela fw-600" @tap="(e:any) => setTabIndex(7, e)" :class="{ 'tab-active': tabIndex == 7 }">
					{{ $t('order.已关闭') }}
				</view>
			</view>
		</scroll-view>
		<swiper class="swiper" :current="tabIndex" @change="(e:any) => setTabIndex(e.detail.current)">
			<swiper-item v-for="(item, index) in orderList" :key="index">
				<scroll-view scroll-y @scrolltolower="item.handleQueryPage()" lower-threshold="60">
					<view class="e-m-t-20 e-p-l-20 e-p-r-20" v-for="order in item.list" :key="order.id" @tap="$goTo('/pages/systemPay/order/details/index', { id: order.id })">
						<order-goods-card :receivingStatus="order.receivingStatus" :store="order.store" :goodsList="order.deputys" :isJump="false" goodsLink="/pages/systemPay/order/details/index">
							<template #statusText>
								<text class="c-primary e-m-r-10" v-if="order.orderPayType === 'OFFLINE' && order.receivingStatus === 0">
									{{ $t('order.审核中') }}
								</text>
								<text class="c-primary e-m-r-10" v-if="order.orderPayType === 'CASH' && order.receivingStatus === 0">
									{{ $t('order.待确认') }}
								</text>
								<!--  -->
								<text v-else :class="{ 'c-primary': orderStatusText[order.receivingStatus] && orderStatusText[order.receivingStatus].cssClass === '0' }">
									{{ $selectDictLabel(orderStatusText, order.receivingStatus) }}
								</text>
							</template>

							<template #button="{ goods, receivingStatus }">
								<goods-status
									:goods="goods"
									:receivingStatus="receivingStatus"
									@tap.native="$goTo('/pages/systemPay/order/details/index', { id: order.id })"
									@refund="(id:string, goodsId:string) => applyRefund(id, goodsId, order.orderId)"
								></goods-status>
							</template>
							<template #deduction="{goods}" >
								<view v-if="goods.formJson" @tap.stop>
									<order-goods-form  :formJson="goods.formJson"  :price="goods.deputyMoney"
									:number="goods.commodityCount"></order-goods-form>
								</view>
								
							</template>
						</order-goods-card>
						
						<view class="bg-white">
							<view class="text-right e-flex e-flex-end">
								<text class="text-right	e-p-r-30 w-600 ">抵扣：{{$unitEn}}{{ order.orderMoneyDeduction }}</text>
							</view>
							<view class="text-right e-flex e-flex-end">
								<text class="text-right e-p-30 w-600 ">{{ $t('order.实付') }}{{$unitEn}}{{ order.orderMoneyPay }}</text>
							</view>
							<view class="e-flex e-flex-end e-p-b-10">
								<view class="" v-if="[1,2,3,4,10].includes(order.receivingStatus) && order.orderRefundStatus !== 2 && order.orderRefundStatus !== 1">
									<view class="recycle-btn e-flex-xy-center" v-if="order.hasInvoice === 0" @tap.stop="handleApplyInvoce(order.orderId)">
										<text class="e-font-30 c-333">申请开票</text>
									</view>
									<view class="recycle-btn e-flex-xy-center" v-else-if="order.hasInvoice === 1">
										<text class="e-font-30 c-333">查看发票</text>
									</view>
								</view>
								<order-button
									class="shadow-f3"
									:info="order"
									:isDetail="false"
									v-if="buttonShow(order, index)"
									@refund="$goTo('/pages/systemPay/order/details/index', { id: order.id, refund: 1 })"
									@cancelRefund="cancelRefund(order.orderId)"
									@cancel="$goTo('/pages/systemPay/order/details/index', { id: order.id, cancel: 1 })"
									@receiving="receiving(order.orderId, order.id, order.orderPayType, order.tranId)"
									@pay="$goTo('/pages/systemPay/order/details/index', { id: order.id, pay: 1 })"
								></order-button>
							</view>
							
						</view>

					</view>
					<empty :text="$t('user.暂无记录')" :icon="$staticPath('default_img.png')" v-if="item.isEmpty"></empty>
					<load-more v-else :showLoad="item.showLoad"></load-more>
				</scroll-view>
			</swiper-item>
		</swiper>
		
		<invoiceVue v-model:value="showInvoice" @close="showInvoice =false" @submit="submitInvoice"></invoiceVue>
	</view>
</template>

<script setup lang="ts">
import { ref, reactive,watch, computed } from 'vue';
import { getOrderList, postCancelRefundOrder, postOrderReceiving,applyInvoices } from '@/common/request/api';
import type { OrderItem } from '@/common/request/api';
import { useCurrentInstance, useQueryPage } from '@/common/hooks';
import orderButton from './child/order-button.vue';
import goodsStatus from './child/goods-status.vue';
import { onLoad, onShow, onPullDownRefresh } from '@dcloudio/uni-app';
import { useOrder, useInit } from '@/common/stores';
import { storeToRefs } from 'pinia';
import { sys, wxOpenBusinessView } from '@/common/utils';
import { useI18n } from 'vue-i18n';
import invoiceVue from './child/invoice.vue'

const ctx = useCurrentInstance();
const {t} = useI18n()
const orderStore = useOrder();
const { orderStatusText } = storeToRefs(orderStore);
const { orderIconText,AppSkin } = storeToRefs(useInit());

const recyclebox = computed(() => {
	return {
		backgroundColor: AppSkin.primary.replace('1)', '0.05)'),
		color:AppSkin.primary,
		borderColor:AppSkin.primary.replace('1)', '0.1)')
	}
})

const showInvoice = ref(false)
const orderId = ref()
const handleApplyInvoce = (id)=> {
	console.log(id,'id')
	orderId.value = id
	showInvoice.value = true
}
const submitInvoice = (data) => {
	showInvoice.value = false
	uni.showLoading()
	applyInvoices({orderId:orderId.value,hasInvoice:1,...data}).then(res => {
		if (res.code == 200) {
			ctx.$toastApp('申请成功')
			orderList[tabIndex.value].handleUpdate();
		}
	}).finally(() => {
		uni.hideLoading()
	})
}

const tabIndex = ref(0);
const orderList = reactive([
	useQueryPage({
		api: getOrderList,
		option: {
			params: {
				receivingType: 0
			}
		},
		pageSize:10
	}),
	useQueryPage({
		api: getOrderList,
		option: {
			params: {
				receivingType: 0,
				receivingStatus: 0
			}
		},
		pageSize:10
	}),
	useQueryPage({
		api: getOrderList,
		option: {
			params: {
				receivingType: 0,
				receivingStatus: 1
			}
		},
		pageSize:10
	}),
	useQueryPage({
		api: getOrderList,
		option: {
			params: {
				receivingType: 0,
				receivingStatus: 2
			}
		},
		pageSize:10
	}),
	useQueryPage({
		api: getOrderList,
		option: {
			params: {
				receivingType: 0,
				receivingStatus: 3
			}
		},
		pageSize:10
	}),
	useQueryPage({
		api: getOrderList,
		option: {
			params: {
				receivingType: 0,
				receivingStatus: 6
			}
		},
		pageSize:10
	}),
	useQueryPage({
		api: getOrderList,
		option: {
			params: {
				receivingType: 0,
				receivingStatus: 4
			}
		},
		pageSize:10
	}),
	useQueryPage({
		api: getOrderList,
		option: {
			params: {
				receivingType: 0,
				receivingStatus: 5
			}
		},
		pageSize:10
	})
]);
const scrollLeft = ref(0);

const setTabIndex = (index: number, e?: any) => {
	console.log(e, 'e');
	tabIndex.value = index;
	
	// 此处为屏幕宽度
	const windowWidth = sys().windowWidth;
	const halfWidth = windowWidth / 2;
	if (e) {
		scrollLeft.value = e.currentTarget.offsetLeft - halfWidth;
	} else {
		// 滑动页面的时候
		scrollLeft.value = (tabIndex.value + 1) * (windowWidth / 5) - halfWidth;
	}
};

watch(tabIndex,(v) => {
	if (orderList[v].list.length === 0) {
		loading.value = true;
		orderList[v].handleRefresh().finally(() => {
			loading.value = false;
		});
	}
})
const buttonShow = (order: OrderItem, index: number) => {
	return order.receivingStatus !== 4 && !((order.orderPayType === 'OFFLINE' && index === 1) || (order.orderPayType === 'OFFLINE' && index === 0));
};

const cancelRefund = (id: string) => {
	postCancelRefundOrder(id).then(() => {
		orderList[tabIndex.value].handleUpdate();
		ctx.$toastApp(t('common.操作成功'));
	});
};
const handleReceive = (orderId:string, id:string|number) => {
	postOrderReceiving({
		orderId
	}).then((res) => {
		ctx.$goRedirectTo('/pages/order/success', {
			type: 3,
			id
		});
	});
};
const handleReceiveTips = (orderId: string, id: string|number) => {
	ctx.$showModal({
		content: t('order.确认要收货吗'),
		success: (res) => {
			if (res.confirm) {
				handleReceive(orderId, id);
			}
		}
	});
};
// 确认收货
const receiving = (orderId: string, id: string|number, orderPayType: string, tranId?: string) => {
	if (orderPayType === 'WX'&&tranId) {
		wxOpenBusinessView({
			transaction_id: tranId
		}).then((e) => {
			console.log('success', e);
			if (e.status === 'success') {
				handleReceive(orderId, id);
			} else if (e.status === 'fail') {
				ctx.$toastApp(e.status);
			} else if (e.status === 'cancel') {
				console.log(e.extraData, 'e.extraData');
			}
		}).catch(res => {
			if(res.code === 500){
				ctx.$toastApp('确认失败，请重试');
			}else if(res.code === 401){
				handleReceiveTips(orderId, id);
			}
		})
	} else {
		handleReceiveTips(orderId, id);
	}
};

// 申请退款
const applyRefund = (id: string, goodsId: string, orderId: string) => {
	ctx.$goTo(`/pages/order/refund/apply?id=${id}&goodsId=${goodsId}&orderId=${orderId}`);
};

const loading = ref(true);
let  isLoad = true
onLoad((opt) => {
	if (opt?.type) {
		setTabIndex(Number(opt.type))
	}else{
		orderList[tabIndex.value].handleRefresh().finally(() => {
			loading.value = false
		});
	}

	if (!orderStatusText.value.length) {
		orderStore.getOrderStatusText();
	}
});
onShow(() => {
	if(!isLoad){
		orderList[tabIndex.value].handleUpdate().finally(() => {
			loading.value = false
		});
	}
	isLoad = false
	
});

onPullDownRefresh(() => {
	orderList[tabIndex.value].handleRefresh().finally(() => {
		uni.stopPullDownRefresh();
	});
});
</script>

<style lang="scss" scoped>
.shadow-f3 {
	box-shadow: 0px -2rpx 0px 0px #f3f3f3;
}

.tab {
	width: 100%;

	> view {
		background-color: white;
		height: 90rpx;
		line-height: 90rpx;
		flex: 0 0 25%;
	}

	.tab-active {
		&::before {
			content: '';
			position: absolute;
			width: 46rpx;
			height: 6rpx;
			background: var(--color-primary);
			border-radius: 3rpx;
			bottom: 0;
			left: calc(50% - 23rpx);
		}
	}
}

.swiper {
	height: calc(100vh - 90rpx);

	scroll-view {
		height: 100%;
	}

	::v-deep {
		.goods-info2 {
			padding: 0 !important;
		}
	}
}
.recycle-box {
		display: inline-block;
		padding: 10rpx 20rpx 8rpx 20rpx;
		border-radius: 32rpx 32rpx 0px 32rpx;
		border: 1px solid;
	}
	.recycle-btn {
		width: 172rpx;
		height: 70rpx;
		border-radius: 36rpx;
		border: 1rpx solid #B4B4B4;
	}
</style>
